package tcm.com.gistone.util;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * @author wangfan
 *
 */
@Component
public class EmailUtils {
    @Value("${email.address}")
    public  String email_address ;
    @Value("${email.password}")
    public  String email_password ;
    @Value("${email.host}")
    public  String email_host;
    @Value("${email.port}")
    public  String email_port ;

    private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class);

    public  boolean sendHtmlMail(String subject,String content,String receiver){


        boolean result = true;

        try{
            JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();  

            senderImpl.setHost(email_host);
            senderImpl.setPort(Integer.valueOf(email_port));
            senderImpl.setUsername(email_address);
            senderImpl.setPassword(email_password);
            senderImpl.setDefaultEncoding("UTF-8");
            Properties prop = new Properties();  
            prop.put("mail.smtp.auth", "true");
            prop.put("mail.smtp.ssl.enable", "false");
            prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            senderImpl.setJavaMailProperties(prop);  

            MimeMessage mailMessage = senderImpl.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);  

            messageHelper.setTo(receiver);
            messageHelper.setFrom(email_address);
            messageHelper.setSubject(subject);
            messageHelper.setText(content,true);

            senderImpl.send(mailMessage);
        } catch (Exception e) {
            
            result = false;
            logger.info("EmailUtils.method [sendHtmlMail]: email send result-" + result +",error message-" + e);
        }

        return result;
    }

}